<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\MemberLikes;
use think\Exception;
use vm\com\BaseModel;
use vm\com\BaseService;

class MemberLikesService extends BaseService
{
    /**
     * @return BaseService|MemberProfileService
     */
    private function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return MemberLikes
     */
    protected function getModel()
    {
        return new MemberLikes();
    }

    public function save($userId, $memberProfileId)
    {
        if($this->info([
            'user_id' => $userId,
            'member_profile_id' => $memberProfileId
        ])) {
            $this->delete([
                'user_id' => $userId,
                'member_profile_id' => $memberProfileId
            ]);
            $this->getMemberProfileService()->decrease('likes', ['id' => $memberProfileId]);
        } else {
            $rights = $this->getMemberProfileService()->getVipRightsByUserId($userId);
            if($rights['make_friends_amount'] != -1
                && $rights['make_friends_amount'] <= $this->count(['user_id' => $userId])) {
                throw new Exception('您当前最多可关注'.$rights['make_friends_amount'].'个会员');
            }
            $this->create([
                'user_id' => $userId,
                'member_profile_id' => $memberProfileId,
                'add_time' => time()
            ]);
            $this->getMemberProfileService()->increase('likes', ['id' => $memberProfileId]);
        }
    }
}